﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RoboServ
{
    public partial class RoboServForm : Form
    {

        XBeeSerial xb;

        private static RoboServForm thisForm = null;

        public RoboServForm()
        {
            InitializeComponent();

            thisForm = this;
            xb = new XBeeSerial();

            refreshPortNames();

        }

        public static void log(string s, params object[] args)
        {
            log(String.Format(s, args));
        }

        private void appendText(string text)
        {
            tbLog.AppendText(text+"\n");
        }

        public delegate void AppendTextCallback(string text);

        public static void log(String s) {
            if (thisForm != null)
            {
                thisForm.tbLog.Invoke(new AppendTextCallback(thisForm.appendText),
                    new object[] { s });
            }
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (btnOpen.Text == "Open")
            {
                if (cbPortNames.SelectedItem != null)
                {
                    xb.open((string)cbPortNames.SelectedItem, 38400);
                    btnOpen.Text = "Close";
                }
            }
            else
            {
                if (xb.IsOpen)
                {
                    xb.close();
                    btnOpen.Text = "Open";
                }
            }
        }

        private void refreshPortNames()
        {
            cbPortNames.Items.Clear();
            foreach (string s in SerialPort.GetPortNames())
            {
                cbPortNames.Items.Add(s);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            refreshPortNames();
        }

        private void RoboServForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            if(xb.IsOpen) xb.close();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (xb.IsOpen)
            {
                xb.sendRX(0x40, 0x03, new byte[5] { 0x00, 0x31, 0x30, 0x30, 0x0D });
            }
        }
    }
}
